package com.by.service.impl;

import com.by.bean.Car;
import com.by.service.CarService;
import com.by.utils.RedisUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class CarServiceImpl3 implements CarService {
    private final RedisUtils redisUtils;

    public CarServiceImpl3(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void addCar(Car car) {
        String key = "userTest:id:1";
        List<Car> carlist = new ArrayList<Car>();
        //取数据
        Object obj = redisUtils.get(key);
        if (obj == null) {
            //说明不存在
            carlist = new ArrayList<>();
            carlist.add(car);
        } else {
            //如果存在obj
            carlist = (List<Car>) obj;
            //遍历
            Iterator<Car> it = carlist.iterator();
            boolean isExist = false;
            while (it.hasNext()) {
                //获取当前对象
                Car tmp = it.next();
                if (tmp.getId() == car.getId()) {
                    //找到了 修改数量
                    int tmpNum = tmp.getNum();
                    tmpNum++;
                    tmp.setNum(tmpNum);
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                //如果没有找到，添加
                carlist.add(car);
            }
        }
        redisUtils.setEx(key, carlist,10);
    }

    @Override
    public List<Car> getCarList() {
        String key = "userTest:id:1";
        List<Car> list = null;
        Object o = redisUtils.get(key);
        if (o != null) list = (List<Car>) o;
        return list;
    }
}
